<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class GoodsStoreStock extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'store_id', 'goods_id', 'stock_num',
    ];

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function goods()
    {
        return $this->belongsTo(Goods::class);
    }

    public static function addStock($storeId, $goodsId, $stockNum)
    {
        DB::transaction(function () use ($storeId, $goodsId, $stockNum, &$goodsStoreStock) {
            $goodsStoreStock = GoodsStoreStock::firstOrNew([
                'store_id' => $storeId,
                'goods_id' => $goodsId
            ], [
                'stock_num' => 0
            ]);

            $goodsStoreStock->stock_num += $stockNum;
            $goodsStoreStock->save();

            if ($goodsStoreStock->stock_num < 0)
                throw new \Exception('库存不足');

            GoodsStoreStockLog::create([
                'store_id' => $storeId,
                'goods_id' => $goodsId,
                'stock_num' => $stockNum,
                'user_id' => Auth::id()
            ]);
        });

        return $goodsStoreStock;
    }
}
